package fun.codedesign.principle.advice151.a109;

import org.junit.Test;

import fun.codedesign.principle.advice151.Notice;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 
 * @author zengjian
 * @create 2018-07-08 15:58
 * @since 1.0.0
 */
@Notice("采用getGenericSuperClass来定位实际的继承的泛型参数，可用于ORM中的Dao层")
public class GenericTypeUtils {

    @SuppressWarnings("all")
    public static <T> Class<T> getGenericType(Class<?> src) {
        Type type = src.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType pt = (ParameterizedType) type;
            Type[] types = pt.getActualTypeArguments();
            if (types.length > 0 && types[0] instanceof Class) {
                return (Class<T>) types[0];
            }
        }
        return (Class<T>) Object.class;
    }

    @Test
    public void test() {
        UserDao dao = new UserDao();
        dao.hello();
    }

}

abstract class BaseDao<T> {

    public void hello() {
        Class<?> clazz = GenericTypeUtils.getGenericType(this.getClass());
        System.out.println(clazz);
    }
}

class UserDao extends BaseDao<String> {

}
